package cc.ccoke.algorithms.primary.chapter03;


/**
 * 用数组结构实习那大小固定的栈,并实现返回栈中最小元素
 * @author ccoke
 */
public class Stack {
    private static final int DEFAULT_LENGTH = 10;

    private int[] data;

    /**
     * 记录最小值
     */
    private int[] min;

    private int size = 0;

    private int index = -1;

    public Stack(int length) {
        this.data = new int[length];
        this.min = new int[length];
    }

    public Stack() {
        this.data = new int[DEFAULT_LENGTH];
        this.min = new int[DEFAULT_LENGTH];
    }


    /**
     * 入栈
     */
    public void push(int item) {
        if (size == data.length) {
            return;
        }
        data[++ index] = item;
        min[index] = (size == 0) ? item : (item < data[index - 1]) ? item: data[index - 1];
        size ++;
    }

    /**
     * 出栈
     */
    public int pop() throws Exception {
        if (size == 0) {
            throw new Exception("stack is empty!");
        }
        size --;
        return data[index--];
    }

    /**
     * 获取最小值
     */
    public int getMin() {
        return min[index];
    }

    /**
     * 获取栈中元素个数
     */
    public int getSize() {
        return size;
    }

    public static void main(String[] args) throws Exception {
        Stack stack = new Stack();
        stack.push(4);
        stack.push(3);
        stack.push(5);
        stack.push(6);
        stack.push(5);
        stack.push(3);
        stack.push(2);
        stack.push(1);
        stack.push(1);
        stack.push(8);
        System.out.println("size:" + stack.getSize());
        System.out.println("min:" + stack.getMin());
        System.out.println("pop:" + stack.pop());
        System.out.println("pop:" + stack.pop());
        System.out.println("pop:" + stack.pop());
        System.out.println("pop:" + stack.pop());
        System.out.println("size:" + stack.getSize());
        System.out.println("min:" + stack.getMin());
    }

}
